<template>
  <div class="component-upload-image">
    <div>
      <img :src="imgUrl" @click="imgClick" style="width: 110px;height:110px;" />
    </div>

    <el-button @click="onDownload">下载</el-button>
    <el-button @click="onDelete" :disabled="isdisabled">删除</el-button>
    <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body @close="closeDialog">
      <el-row>
        <el-button type="primary" @click="zoomIn">
          <el-icon :size="20"><ZoomIn /></el-icon>
        </el-button>
        <el-button type="primary" @click="zoomOut">
          <el-icon :size="20"><ZoomOut /></el-icon>
        </el-button>
      </el-row>
      <el-row ref="previewRow" :style="rowWidth">
        <img :src="imgUrl" class="preview-img" ref="previewImg" :style="imgWidth" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { upLoadFile, downLoadFile, deleteFile } from "@/api/system/attachFile.js";
const props = defineProps({
  attachId: String,
  fileIndex: Number,
  isdisabled: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits();
const { proxy } = getCurrentInstance();

const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const imgUrl = computed(
  () => baseUrl + "/attachment/downLoadFile?attachId=" + encodeURIComponent(props.attachId)
);
// 预览
function imgClick(file) {
  dialogVisible.value = true;
}

//下载附件
const onDownload = () => {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId="+ encodeURIComponent(props.attachId);
}

//删除附件
const onDelete = () => {
  deleteFile(props.attachId).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除图片成功");
      emit('deleteImage', props.attachId, props.fileIndex);
    } else {
      proxy.$modal.msgError("删除图片失败");
    }
  });
}

const imgWidth = ref({
  width: '',
  display: 'block',
  margin: '0 auto'
})
const rowWidth = ref({
  width: ''
})
const previewImg = ref()
const previewRow = ref()

const zoomIn = () => {
  const originWidth = previewImg.value.clientWidth
  const originRowWidth = previewRow.value.$el.clientWidth
  imgWidth.value.width = originWidth + 20 + 'px'
  if(originWidth + 20  >= originRowWidth){
    rowWidth.value.width = originRowWidth + 20 + 'px'
  }
}
const zoomOut = () => {
  const originWidth = previewImg.value.clientWidth
  const originRowWidth = previewRow.value.$el.clientWidth
  if(originWidth >= 300){
    imgWidth.value.width = originWidth - 20 + 'px'
    if(originRowWidth > 760){
      rowWidth.value.width = originRowWidth - 20 + 'px'
    }
  }
}
const closeDialog = () => {
  imgWidth.value.width = ''
  rowWidth.value.width = ''
}


</script>
  
<style lang="scss" scoped>
.el-dialog{
  .el-dialog__body{
    overflow: auto;
    .el-row{
      padding: 10px 0;
    }
  }
}
</style>
<style>
.el-dialog__body{
  overflow: auto;
  padding: 10px 20px!important;
}
</style>